/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    class TreeTuple
    {
    public:
        int val;
        int leftID;
        int rightID;
        TreeTuple(int val, int leftID, int rightID) : val(val), leftID(leftID), rightID(rightID) {}
        bool operator==(const TreeTuple &other) const
        {
            return this->val == other.val && this->leftID == other.leftID && this->rightID == other.rightID;
        }
    };

    // 仿照官方题解的hash函数
    class TreeTupleHash
    {
    public:
        hash<int> hashFun = hash<int>();
        size_t operator()(const TreeTuple &t) const
        {
            return (hashFun(t.val) << 24) ^ (hashFun(t.leftID) << 8) ^ hashFun(t.rightID);
        }
    };

    vector<TreeNode *> findDuplicateSubtrees(TreeNode *root)
    {
        preOrderTraversal(root);
        return vector<TreeNode *>(result.begin(), result.end());
    }

    int preOrderTraversal(TreeNode *tree)
    {
        if (tree == nullptr)
        {
            return 0;
        }
        else
        {
            int leftSubTreeID = preOrderTraversal(tree->left);
            int rightSubTreeID = preOrderTraversal(tree->right);

            TreeTuple thisTreeTuple{tree->val, leftSubTreeID, rightSubTreeID};

            if (treeMap.find(thisTreeTuple) != treeMap.end())
            {
                result.insert(treeMap[thisTreeTuple].second);
                return treeMap[thisTreeTuple].first;
            }
            else
            {
                treeMap.insert({thisTreeTuple, {++treeID, tree}});
                return treeID;
            }
        }
    }

    unordered_map<TreeTuple, pair<int, TreeNode *>, TreeTupleHash> treeMap{0, TreeTupleHash()};
    unordered_set<TreeNode *> result;
    int treeID = 0;
};